import {
  DefaultCrudRepository,
  juggler,
  HasManyRepositoryFactory,
  repository,
  BelongsToAccessor,
} from '@loopback/repository';
import { TodoList, Todo, User } from '../models';
import { inject, Getter } from '@loopback/core';
import { TodoRepository } from './todo.repository';
import { MysqlLocalDataSource } from '../datasources';
import { UserRepository } from './user.repository';

export class TodoListRepository extends DefaultCrudRepository<TodoList,
  typeof TodoList.prototype.id> {

  public readonly todos: HasManyRepositoryFactory<Todo, typeof TodoList.prototype.id>;

  public readonly user: BelongsToAccessor<User, typeof TodoList.prototype.id>

  constructor(
    @inject('datasources.mysqlLocal') dataSource: MysqlLocalDataSource,
    @repository.getter('TodoRepository')
    protected todoRepositoryGetter: Getter<TodoRepository>,
    @repository.getter('UserRepository')
    protected userRepositoryGetter: Getter<UserRepository>,
  ) {
    super(TodoList, dataSource);

    this.todos = this.createHasManyRepositoryFactoryFor(
      'todos',
      todoRepositoryGetter,
    );

    this.user = this.createBelongsToAccessorFor(
      'user',
      userRepositoryGetter
    )
  }

  public findByTitle(title: string) {
    return this.findOne({ where: { title } });
  }
}
